﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAttack : MonoBehaviour
{
    // 攻击力
    public float minDamage = 10;
    public float maxDamage = 20;
    public float critRate = 0.5f;           // 暴击率
    public float critMultiplier = 2;        // 暴击伤害倍数
    // 击退效果
    public float knockback = 1;

    private bool isAttacking;

    // 击中的敌人，防止同一个敌人被击中多次
    private List<EnemyMovement> attackedEnemies = new List<EnemyMovement>();

    public void Attack()
    {
        if (isAttacking)
        {
            return;
        }
        isAttacking = true;
        gameObject.SetActive(true);
        // 鼠标位置 - 人物位置
        Vector2 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        // 计算角度
        float angle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, 0, angle);
    }

    public void AttackFinish()
    {
        gameObject.SetActive(false);
        isAttacking = false;
        attackedEnemies.Clear();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {
            EnemyMovement enemy = collision.GetComponent<EnemyMovement>();
            if (attackedEnemies.Contains(enemy))
            {
                return;
            }
            attackedEnemies.Add(enemy);

            enemy.Injured(Damage(), knockback);
        }
    }

    private float Damage()
    {
        float damage = Random.Range(minDamage, maxDamage);
        damage = Mathf.Round(damage);

        // 暴击判定
        float critRandom = Random.Range(0, 1f);
        if (critRandom <= critRate)
        {
            damage *= critMultiplier;
        }
        return damage;
    }
}
